﻿using System;
using System.Collections.Generic;
using System.Linq;
namespace WCF.Common.DAL
{
    public class UserObjectDAL : BaseDAL
    {
        /// <summary>获取表数据</summary>
        /// <returns>List</returns>
        public List<UserObject> Gets()
        {
            // rs=0表示该记录已经被删除
            return GetDataContext().UserObject.ToList();
        }
        /// <summary>增加数据</summary>
        /// <param name="users"></param>
        /// <returns>OperateResult</returns>
        public OperateResult Insert(UserObject user)
        {
            try
            {
                var context = GetDataContext();
                context.UserObject.InsertOnSubmit(user);
                context.SubmitChanges();
            }
            catch (Exception ex)
            {
                return new OperateResult() { IsSuccess = false, Message = ex.Message };
            }
            return new OperateResult() { IsSuccess = true };
        }
        /// <summary>删除数据</summary>
        /// <param name="id"></param>
        /// <returns>OperateResult</returns>
        public OperateResult Delete(string id)
        {
            try
            {
                var context = GetDataContext();

                var obj = context.UserObject.Single(p => p.ID == id);
                context.UserObject.DeleteOnSubmit(obj);
                context.SubmitChanges();
            }
            catch (Exception ex)
            {
                return new OperateResult() { IsSuccess = false, Message = ex.Message };
            }
            return new OperateResult() { IsSuccess = true };
        }
        /// <summary>修改数据</summary>
        /// <param name="user"></param>
        /// <returns>OperateResult</returns>
        public OperateResult Update(UserObject user)
        {
            try
            {
                var context = GetDataContext();
                if (context.UserObject.Any(p => p.ID == user.ID))
                {
                    var obj = context.UserObject.Single(p => p.ID == user.ID);
                    obj.Caption = user.Caption;
                    obj.Code = user.Code;
                    obj.Describe = user.Describe;
                    context.SubmitChanges();
                }
            }
            catch (Exception ex)
            {
                return new OperateResult() { IsSuccess = false, Message = ex.Message };
            }
            return new OperateResult() { IsSuccess = true };
        }

        /// <summary>根据共享平台接口KEY查用户</summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public UserObject SearchByKey(string key)
        {
            UserObject result = null;
            var users = this.Gets().Where(p => p.Code == key);
            if (users != null)
            {
                result = users.Single();
            }
            return result;
        }
    }
}